<?php

class BidModel extends CFormModel
{

    const ACTION_COST = 'COST';
    const ACTION_EARN = 'EARN';
    
    public $bid_source_type;

    public $bid_type;

    public $action;

    public $note;

    public $customer_id;
    
    protected $_amount = 0;

    protected $_transaction = false;

    public function setAmount($amount)
    {
        if ($amount < 0) {
            $this->action = self::ACTION_COST;
        } else {
            $this->action = self::ACTION_EARN;
        }
        return $this->_amount = $amount;
    }

    public function getAmount()
    {
        return $this->_amount;
    }

    public function rules(){
       return array(
           array(
               'customer_id',
               'exist',
               'attributeName' => 'customer_id',
               'className'     => 'CustomerBidInfo',
           ),
           array(
                'bid_source_type,bid_type,action,note,customer_id,amount','safe'
           )
       );
    }
    
    public function updateBidInfo(){
        $bidSQL = '
            UPDATE
                `customer_bid_info`
            SET
                `bid_num` = @bid_amount := bid_num + '.$this->getAmount().'
            WHERE
                `customer_id` = "'.$this->customer_id.'"
            AND
                `bid_type` = "'.$this->bid_type.'"
        ';
        $updateInfoBid = Yii::app()->db->createCommand($bidSQL)->execute();
        
        if (!$updateInfoBid){
            throw new CException(Yii::t('yii','Update Bid Info Error'));
        }
        
        $updateAfterBidSQL = 'select @bid_amount as bid_amount';
        $updateAfterBid = Yii::app()->db->createCommand($updateAfterBidSQL)->queryRow();
        if ($updateAfterBid['bid_amount'] < 0){
            throw new CException(Yii::t('yii','Update Bid Info Bid Negative'));
        }
        
        return $this;
    }
    
    public function addHistory(){
        $bidhistory = new BidHistory();
        $bidhistory->attributes = array(
            'amount' => $this->amount,
            'bid_source_type' => $this->bid_source_type,
            'customer_id' => $this->customer_id,
            'bid_type' => $this->bid_type,
            'action' => $this->action,
            'note' => $this->note
        );
        $addHistory = $bidhistory->save();
        if (!$addHistory){
            throw new CException(Yii::t('yii', 'Add History Error '.json_encode($bidhistory->getErrors())));
        }
        return $this;
    }
    
    public function save(){        
        $this->updateBidInfo()->addHistory();     
    }
       
}